﻿namespace h101
{


    

  public class ListNode {
      public int val;
      public ListNode next;
      public ListNode(int x) { val = x; }
  }
    public class Solution {
        public ListNode ReverseBetween(ListNode head, int m, int n) {
            int i = 1;
            if(head.next == null){
                return head;
            }
            ListNode cur = head;
            ListNode pre = null;
            ListNode node1 = null;
            ListNode node2 = null;
            ListNode node3 = null;
            ListNode node4 = null;
            while(i<m){
                pre = cur;
                cur = cur.next;
                i++;
            }
            if(i == m){
                node1 = pre;
                node2 = cur;
                pre = cur;
                cur = cur.next;
            }
            while(i<n){
                ListNode temp = cur.next;
                cur.next = pre;
                pre = cur;
                cur = temp;
                i++;
            }
            if(i == n){
                node3 = pre;
                node4 = cur;
            }
            node2.next = node4;
            if(m == 1){
                return node3;
            }else{
                node1.next = node3;
                return head;
            }
        }
    }

}